#include "HttpResponse.h"
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <stdio.h>
#define ResHeaderSize 16
//初始化
struct HttpResponse* HttpResponseInit()
{
    struct HttpResponse* response = (struct HttpResponse*)malloc(sizeof(struct HttpResponse));
    response->headerNum = 0;
    response->headers = (struct ResponseHeader*)malloc(sizeof(struct ResponseHeader) * ResHeaderSize);
    response->statusCode = Unknown;
    //初始化数组
    bzero(response->headers, sizeof(struct ResponseHeader) * ResHeaderSize);
    bzero(response->statusMsg, sizeof(char) * 128);
    bzero(response->fileName, sizeof(char) * 128);
    //函数指针
    response->sendDataFunc = NULL;

    return response;
}

//销毁
void httpResponseDestroy(struct HttpResponse* response)
{
    if(response != NULL)
    {
        free(response->headers);
        free(response);
    }
}

//添加响应头
void httpResponseAddHeader(struct HttpResponse* response, const char* key, const char* value)
{
    if(response == NULL || key == NULL || value == NULL)
    {
        return;
    }
    strncmp(response->headers[response->headerNum].key, key, strlen(key));
    strncmp(response->headers[response->headerNum].value, value, strlen(value));
    response->headerNum++;
}

//组织http响应数据
void httpResponsePrepareMsg(struct HttpResponse* response, struct Buffer* sendBuf, int socket)
{
    //状态行
    char tmp[1024] = { 0 };
    sprintf(tmp, "HTTP/1.1 %d %s\r\n", response->statusCode, response->statusMsg);
    bufferAppendString(sendBuf, tmp);
    //响应头
    for(int idx = 0; idx < response->headerNum; idx++)
    {
        sprintf(tmp, "%s: %s\r\n", response->headers[idx].key, response->headers[idx].value);
    }
    bufferAppendString(sendBuf, tmp);
    //空行
    bufferAppendString(sendBuf, "\r\n");
#ifndef  MSG_SEND_AUTO
    bufferSendData(sendBuf, socket);
#endif
    //回复的数据
    response->sendDataFunc(response->fileName, sendBuf, socket);
}